﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FinalOnlineLibrary.Models;
using FinalOnlineLibrary.DAL;

namespace OnlineLibrary.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        OnlineLibrary.ToLinq.OnlineLibraryDBDataContext user = new OnlineLibrary.ToLinq.OnlineLibraryDBDataContext();
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        //IEnumerable<OnlineLibrary.ToLinq.tblUser> list = user.tblUsers.ToList();
        public ActionResult Index(OnlineLibrary.ToLinq.tblUser collection)
        {
            //var exist_user = from e_user in user.tblUsers where e_user.UserName == collection.UserName select e_user;

            if (collection.UserName != null && collection.PassWord != null)
            {
                var check = DALBooks.GetUser(collection.UserName,collection.PassWord);
                if (check == null) 
                {
                    ViewData["error"] = "Wrong username or password";
                    return View();
                }
                else
                {
                    if (bool.Parse(Session["Login"].ToString()) == false)
                    {
                        Session["Login"] = true;
                        if (check.Role == 1)
                        {
                            Session["Admin"] = true;
                            Session["Guest"] = false;
                            return Redirect("/Admin/Index");
                        }
                        else if (check.Role == 6)
                        {
                            Session["Staff"] = true;
                            Session["Guest"] = false;
                            return Redirect("/User/Index/" + check.Role);
                        }
                        else
                        {
                            Session["User"] = true;
                            Session["Guest"] = false;
                            return Redirect("/User/Details/" + check.Role);
                        }
                    }
                    else
                    {
                        ViewData["error"] = "You have logged in. You must log out to use another account";
                        return View();
                    }

                }

            }
            else
            {
                ViewData["error"] = "Wrong username or password";
                return View();
            }

        }
    }
}
